package md.sv.dbu.receiver;

import md.sv.dbu.DBUExecutor;
import md.sv.dbu.config.jaxb.ReceiveFileType;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

/**
 * @author MG
 */
public class FileMessageReceiver implements MessageReceiver<ReceiveFileType> {
    private static final Logger logger = LoggerFactory.getLogger(FileMessageReceiver.class);

    private SimpleDateFormat sdFormat = new SimpleDateFormat("dd-MM-yyyy");
    private Calendar calendar = Calendar.getInstance();

    private DBUExecutor dbuExecutor;

    public FileMessageReceiver(DBUExecutor dbuExecutor) {
        this.dbuExecutor = dbuExecutor;
    }

    /**
     * This implementation will read all files from a directory
     */
    @Override
    public void receiveMessages(ReceiveFileType config, int maxMessageRead, ReceiverCallback receiverCallback) {
        Date readDate;
        try {
            String varName =dbuExecutor.getGlobalVariablesReplacer().getVariableName(config.getReadDate());
            if (varName != null) {
                readDate = sdFormat.parse(dbuExecutor.getVariables().get(varName).toString());
            } else {
                readDate = sdFormat.parse(config.getReadDate());
            }
        } catch (ParseException e) {
            logger.error("Could not parse read date in ReceiveFile", e);
            return;
        }
        calendar.setTime(readDate);

        String dir = config.getRootDir();
        dir = FilenameUtils.concat(dir, String.valueOf(calendar.get(Calendar.YEAR)));
        dir = FilenameUtils.concat(dir, String.valueOf(calendar.get(Calendar.MONTH) + 1));
        dir = FilenameUtils.concat(dir, String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));

        logger.info("Reading all files from directory: " + dir);
        File fileDir = new File(dir);

        Collection<File> foundFiles = FileUtils.listFiles(fileDir, new IOFileFilter() {
                    @Override
                    public boolean accept(File file) {
                        String fileName = file.getName();
                        String extention = FilenameUtils.getExtension(fileName);
                        return extention != null && extention.equals("xml") && !fileName.contains("!!!");
                    }

                    @Override
                    public boolean accept(File dir, String name) {
                        String extention = FilenameUtils.getExtension(name);
                        return extention != null && extention.equals("xml") && !name.contains("!!!");
                    }
                }, new IOFileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return false;
                    }

                    @Override
                    public boolean accept(File dir, String name) {
                        return false;
                    }
                }
        );

        for (File file : foundFiles) {
            try {
                String msg = FileUtils.readFileToString(file, "UTF-8");
                receiverCallback.onReceive(msg);
            } catch (IOException e) {
                logger.error("IO exception while reading file", e);
            }
        }
    }
}
